package com.netty.chatRoom.server;

import com.netty.chatRoom.message.GroupMembersResponseMessage;
import com.netty.chatRoom.message.LoginRequestMessage;
import com.netty.chatRoom.message.LoginResponseMessage;
import com.netty.chatRoom.protocol.MessageCodecSharable;
import com.netty.chatRoom.protocol.ProcotolFrameDecoder;
import com.netty.chatRoom.server.Handler.*;
import com.netty.chatRoom.server.config.Config;
import com.netty.chatRoom.server.service.UserServiceFactory;
import com.netty.chatRoom.server.session.SessionFactory;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import io.netty.handler.timeout.IdleState;
import io.netty.handler.timeout.IdleStateEvent;
import io.netty.handler.timeout.IdleStateHandler;
import lombok.extern.slf4j.Slf4j;


@Slf4j
public class ChatServer {
    public static void main(String[] args) {
        NioEventLoopGroup boss = new NioEventLoopGroup();
        NioEventLoopGroup worker = new NioEventLoopGroup();

        LoggingHandler LOGGING_HANDLER = new LoggingHandler(LogLevel.DEBUG);
        MessageCodecSharable MESSAGE_CODEC = new MessageCodecSharable();
        ChatRequestMessageHandler CHAT_REQUEST_HANDLER = new ChatRequestMessageHandler();
        LoginRequestMessageHandler LOGIN_REQUEST_HANDLER = new LoginRequestMessageHandler();
        GroupCreateRequestMessageHandler GROUP_CREATER_HANDLER=new GroupCreateRequestMessageHandler();
        GroupChatRequestMessageHandler GROUP_CHAT_HANDLER=new GroupChatRequestMessageHandler();
        GroupMembersRequestMessageHandler GROUP_MEMBER_HANDLER=new GroupMembersRequestMessageHandler();
        GroupJoinRequestMessageHandler GROUP_JOIN_HANDLER=new GroupJoinRequestMessageHandler();
        GroupQuitRequestMessageHandler GROUP_QUIT_HANDLER=new GroupQuitRequestMessageHandler();
        QuitHandler QUIT_HANDLER=new QuitHandler();

        ServerBootstrap serverBootstrap = new ServerBootstrap();
        serverBootstrap.group(boss,worker);
        serverBootstrap.channel(NioServerSocketChannel.class);
        serverBootstrap.childHandler(new ChannelInitializer<NioSocketChannel>() {
            @Override
            protected void initChannel(NioSocketChannel nioSocketChannel) throws Exception {
                nioSocketChannel.pipeline().addLast(new ProcotolFrameDecoder());
                nioSocketChannel.pipeline().addLast(LOGGING_HANDLER);
                nioSocketChannel.pipeline().addLast(MESSAGE_CODEC);
                // 添加心跳检测
                nioSocketChannel.pipeline().addLast(new IdleStateHandler(5,0,0));
                nioSocketChannel.pipeline().addLast(new ChannelDuplexHandler(){
                    @Override
                    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
                        if(evt instanceof IdleStateEvent){
                            IdleStateEvent event=(IdleStateEvent) evt;
                            if (event.state()==IdleState.READER_IDLE){
                                log.debug("在 5s 内没有读到数据了，需要关闭连接");
                                ctx.channel().close();
                            }
                        }
                        super.userEventTriggered(ctx, evt);
                    }
                });
                nioSocketChannel.pipeline().addLast(LOGIN_REQUEST_HANDLER);
                nioSocketChannel.pipeline().addLast(CHAT_REQUEST_HANDLER);
                nioSocketChannel.pipeline().addLast(GROUP_CREATER_HANDLER);
                nioSocketChannel.pipeline().addLast(GROUP_CHAT_HANDLER);
                nioSocketChannel.pipeline().addLast(GROUP_MEMBER_HANDLER);
                nioSocketChannel.pipeline().addLast(GROUP_JOIN_HANDLER);
                nioSocketChannel.pipeline().addLast(GROUP_QUIT_HANDLER);
                nioSocketChannel.pipeline().addLast(QUIT_HANDLER);
            }
        });
        ChannelFuture conFuture = serverBootstrap.bind(Config.getServerPort());
        conFuture.addListener(new ChannelFutureListener() {
            @Override
            public void operationComplete(ChannelFuture channelFuture) throws Exception {
                // 成功建立链接
                channelFuture.channel().closeFuture().addListener(new ChannelFutureListener() {
                    @Override
                    public void operationComplete(ChannelFuture channelFuture) throws Exception {
                        boss.shutdownGracefully();
                        worker.shutdownGracefully();
                        log.debug("【{}】连接已关闭",this);
                    }
                });
            }
        });
    }
}
